package com.wm.web.action;

import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.wm.bean.Restaurant;
import com.wm.bean.Shopkeeper;
import com.wm.bean.User;
import com.wm.comm.Constant;
import com.wm.comm.MD5;
import com.wm.comm.PinYinUtil;
import com.wm.service.RestaurantService;
import com.wm.service.ShopkeeperService;
import com.wm.service.UserService;
import com.wm.web.interceptor.RemoteAddrAware;
import com.wm.web.interceptor.ShopkeeperSessionAware;
import com.wm.web.servlet.*;

public class ShopkeeperReg extends BaseAction implements SessionAware, RemoteAddrAware,ShopkeeperSessionAware{
	private static final Log logger = LogFactory.getLog(ShopkeeperReg.class);
	
	private ShopkeeperService shopkeeperService;
	private RestaurantService restaurantService;

	public ShopkeeperService getShopkeeperService() {
		return shopkeeperService;
	}

	public void setShopkeeperService(ShopkeeperService shopkeeperService) {
		this.shopkeeperService = shopkeeperService;
	}
	
	public RestaurantService getRestaurantService() {
		return restaurantService;
	}

	public void setRestaurantService(RestaurantService restaurantService) {
		this.restaurantService = restaurantService;
	}
	
	private String remoteAddr;
	private ShopkeeperSession shopkeeperSession;
	private Map session;
	
	public String getRemoteAddr() {
		return remoteAddr;
	}

	public void setRemoteAddr(String remoteAddr) {
		this.remoteAddr = remoteAddr;
	}
	
	public ShopkeeperSession getShopkeeperSession() {
		return shopkeeperSession;
	}

	public void setShopkeeperSession(ShopkeeperSession shopkeeperSession) {
		this.shopkeeperSession = shopkeeperSession;
	}
	
	public void setSession(Map session) {
		this.session = session;
	}

	public Map getSession() {
		return session;
	}
	
	private String username;
	private String password;
	private String verifycode;
	private String error;
	private Shopkeeper shopkeeper;

	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}
	
	public String getVerifycode() {
		return verifycode;
	}

	public void setVerifycode(String verifycode) {
		this.verifycode = verifycode;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}
	
	public Shopkeeper getShopkeeper() {
		return shopkeeper;
	}

	public void setShopkeeper(Shopkeeper shopkeeper) {
		this.shopkeeper = shopkeeper;
	}
	
	private String phone;				//联系电话
	private String phone2;				//联系电话2
	private String resName = "";		//饭店名称
	private String address;				//地址
	private String summary;				//饭店简介
	private String notice;				//饭店公告
	private String shopkeeperName;		//店主姓名
	private String qq;					//QQ
	private String webKey;				//网站key
	
	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getPhone2() {
		return phone2;
	}

	public void setPhone2(String phone2) {
		this.phone2 = phone2;
	}

	public String getResName() {
		return resName;
	}

	public void setResName(String resName) {
		this.resName = resName;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getSummary() {
		return summary;
	}

	public void setSummary(String summary) {
		this.summary = summary;
	}

	public String getNotice() {
		return notice;
	}

	public void setNotice(String notice) {
		this.notice = notice;
	}
	
	public String getShopkeeperName() {
		return shopkeeperName;
	}

	public void setShopkeeperName(String shopkeeperName) {
		this.shopkeeperName = shopkeeperName;
	}

	public String getQq() {
		return qq;
	}

	public void setQq(String qq) {
		this.qq = qq;
	}

	public String getWebKey() {
		return webKey;
	}

	public void setWebKey(String webKey) {
		this.webKey = webKey;
	}

	public String execute() {
		try {
			return this.executeMethod(this.getAction());
		} catch (Exception e) {
			logger.error(e);
			return INPUT;
		}
	}

	/**
	 * 初始页
	 */
	public String index(){
		this.setAction("index");
		return "index";
	}
	
	/**
	 * 注册
	 */
	public String save(){
		//验证码正确
		if(!getSessionAuthCode().equalsIgnoreCase(verifycode)){
			this.addFieldError("error", this.getText("error.autherror"));
			this.setError("1");
			return "index";
		}
		
		if(this.getUsername()==null ||this.getUsername().trim().equals("")||this.getUsername().length()>30){
			this.addFieldError("error", this.getText("error.username"));
			this.setError("1");
			return "index";
		}
		
		if(!checkUserName(this.getUsername())){
			this.addFieldError("error", this.getText("error.username"));
			this.setError("1");
			return "index";
		}
		
		if(this.getPassword()==null ||this.getPassword().trim().equals("")||this.getPassword().length()>20){
			this.addFieldError("error", this.getText("error.password"));
			this.setError("1");
			return "index";
		}
		
		if(!checkPassword(this.getPassword())){
			this.addFieldError("error", this.getText("error.password"));
			this.setError("1");
			return "index";
		}
		
		if(this.getUsername()!=null&&!this.getUsername().trim().equals("")){
			Shopkeeper sk = this.getShopkeeperService().findShopkeeperByUserName(this.getUsername());
			if(sk!=null){
				this.addFieldError("error", this.getText("error.username.being"));
				this.setError("1");
				return "index";
			}
		}
		
		Shopkeeper sk = new Shopkeeper();
		MD5 md5 = new MD5();
		sk.setUserName(this.getUsername());
		sk.setUserPwd(md5.getMD5ofStr(this.getPassword()));
		sk.setUserPwdShow(this.getPassword());
		sk.setStatus(0);
		sk.setRegisterTime(new Date());
		sk.setRegisterIP(this.getRemoteAddr());
		sk.setLastTime(new Date());
		sk.setLastIP(this.getRemoteAddr());
		this.getShopkeeperService().saveShopkeeper(sk);
		ShopkeeperSession ss = new ShopkeeperSession();
		ss.setSkid(sk.getId());
		ss.setName(this.getUsername());
		this.getSession().put(Constant.SHOPKEEPER_SESSION_KEY,ss);
		this.setAction("res");
		return "indexAction";
	} 
	
	public String res(){
		ShopkeeperSession ss = (ShopkeeperSession)this.getSession().get(Constant.SHOPKEEPER_SESSION_KEY);
		if(ss.getSkid()==0){
			return "shopkeeper_login";
		}
		this.setAction("restaurant");
		return "restaurant";
	}
	
	public String restaurant(){
		Restaurant restaurant = new Restaurant();
		restaurant.setId(shopkeeperSession.getSkid());
		restaurant.setResName(this.resName);
		restaurant.setResInitials(" ");
		restaurant.setResAnglic(PinYinUtil.getPinYinHeadChar(this.resName));
		restaurant.setResPhonetic(PinYinUtil.getPinYin(this.resName));
		restaurant.setResTaste(" ");
		restaurant.setIsCatenation(0);
		restaurant.setDeliveryPrice(0);
		restaurant.setSpecialMemo(" ");
		restaurant.setSummary(this.summary);
		restaurant.setAddress(this.address);
		restaurant.setDistance(0);
		restaurant.setNotice(this.notice);
		restaurant.setSalesPromotion(" ");
		restaurant.setScore(0);
		restaurant.setScorePeople(0);
		restaurant.setValid(0);
		restaurant.setIsShow(0);
		restaurant.setShowTime((new Date()).getTime());
		restaurant.setOrderNum(0);
		restaurant.setOrderTime(new Date());
		restaurant.setAddTime(new Date());
		restaurant.setDeliverTime(0);
		restaurant.setPhone(this.phone);
		restaurant.setPhone2(this.phone2);
		restaurant.setLogo(" ");
		restaurant.setShopkeeperName(this.shopkeeperName);
		restaurant.setQq(this.qq);
		restaurant.setWebKey(this.webKey);
		try {
			this.getRestaurantService().saveRestaurant(restaurant);
		} catch (Exception e) {
			this.addActionError(this.getText("error.saveerror"));
			return ERROR;
		}
		this.addFieldError("error", this.getText("error.save"));
		this.setError("1");
		//等待审核页
		return "valid";
	}
	
	
	/**
	 * 查询用户名是否存在
	 * @return
	 */
	public String checkUsername(){
		if(this.getUsername()!=null&&!this.getUsername().trim().equals("")){
			this.setShopkeeper(this.getShopkeeperService().findShopkeeperByUserName(this.getUsername()));
		}
		return "ajax";
	}
	
	private String getSessionAuthCode() {
        String auth = (String) this.getSession().get("authCode");
        if(StringUtils.isBlank(auth)){
        	return "";
        }else{
        	return auth;
        }
    }
	
	public static boolean checkUserName(String userName) {
	  //String regex = "([a-z]|[A-Z]|[0-9]|[\\u4e00-\\u9fa5])+";
	  String regex = "^[a-zA-Z0-9_]{6,18}$";
	  Pattern p = Pattern.compile(regex);
	  Matcher m = p.matcher(userName);
	  return m.matches();
	}
	
	public static boolean checkPassword(String password) {
	  //String regex = "([a-z]|[A-Z]|[0-9]|[\\u4e00-\\u9fa5])+";
	  String regex = "^[a-zA-Z0-9_]{6,18}$";
	  Pattern p = Pattern.compile(regex);
	  Matcher m = p.matcher(password);
	  return m.matches();
	}
}
